# -*- coding: utf-8 -*-
import tensorflow as tf
import time
def initializer(context):   
    pass

def handler(environ, start_response):
    context = environ['fc.context']
    request_uri = environ['fc.request_uri']
    for k, v in environ.items():
      if k.startswith('HTTP_'):
        # process custom request headers
        pass
    # do something here
   
    # get request_body    
    try:        
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))    
    except (ValueError):        
        request_body_size = 0   
    request_body = environ['wsgi.input'].read(request_body_size)  

    export_dir = 'models/catdog_models/'
    #export_dir = 'catdog_models'
    with tf.Session(graph=tf.Graph()) as sess:
        tf.saved_model.loader.load(sess, ["serve"], export_dir)
        
        graph = tf.get_default_graph()
        x = graph.get_tensor_by_name("conv2d_1_input:0")
        model = graph.get_tensor_by_name("activation_5/Sigmoid:0")
        result = sess.run(model, {x: eval(request_body.decode())})
        start = time.time()
        result = sess.run(model, {x: eval(request_body.decode())})
        end = time.time()
        exec_time = end - start

    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)

    return [(str(exec_time)).encode(encoding = "utf-8")]